/*
 * ObjectObject.java - ScriptME
 * 
 * Copyright (c) 2009 Cesar Henriques <cesar at alttab.com.ar>.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Based on FESI Project
 * 
 * Contributors:
 * 	Jean-Marc Lugrin - initial API and implementation
 * 	Cesar Henriques <cesar at alttab.com.ar> - J2ME Porting and Extensions
 */
package org.scriptme.ecmascript.data;

import org.scriptme.ecmascript.exceptions.EcmaScriptException;
import org.scriptme.ecmascript.interpreter.Evaluator;

/**
 * Implemements the EcmaScript Object singleton.
 */
public class ObjectObject extends BuiltinFunctionObject {

	/**
	 * Instantiates a new object object.
	 * 
	 * @param prototype
	 *            the prototype
	 * @param evaluator
	 *            the evaluator
	 */
	public ObjectObject(ESObject prototype, Evaluator evaluator) {
		super(prototype, evaluator, "Object", 1);

	}

	// overrides
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.scriptme.ecmascript.data.BuiltinFunctionObject#toString()
	 */
	public String toString() {
		return "<Object>";
	}

	/**
	 * Create an EcmaScript Object for a specified evaluator.
	 * 
	 * @param evaluator
	 *            the Evaluator
	 * 
	 * @return the new object
	 */
	static public ObjectPrototype createObject(Evaluator evaluator) {
		ESObject op = evaluator.getObjectPrototype();
		return new ObjectPrototype(op, evaluator);
	}

	// overrides
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.scriptme.ecmascript.data.ESObject#doConstruct(org.scriptme.ecmascript.data.ESObject,
	 *      org.scriptme.ecmascript.data.ESValue[])
	 */
	public ESObject doConstruct(ESObject thisObject, ESValue[] arguments)
			throws EcmaScriptException {
		ESValue theValue;
		if (arguments.length == 0) {
			theValue = createObject(evaluator);
		} else {
			if (arguments[0] == ESNull.theNull
					|| arguments[0] == ESUndefined.theUndefined) {
				theValue = createObject(evaluator);
			} else {
				theValue = arguments[0].toESObject(evaluator);
			}
		}
		return (ESObject) theValue;
	}

	// overrides
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.scriptme.ecmascript.data.FunctionPrototype#callFunction(org.scriptme.ecmascript.data.ESObject,
	 *      org.scriptme.ecmascript.data.ESValue[])
	 */
	public ESValue callFunction(ESObject thisObject, ESValue[] arguments)
			throws EcmaScriptException {
		ESValue theValue;
		if (arguments.length == 0) {
			theValue = createObject(evaluator);
		} else {
			if (arguments[0] == ESNull.theNull
					|| arguments[0] == ESUndefined.theUndefined) {
				theValue = createObject(evaluator);
			} else {
				theValue = arguments[0].toESObject(evaluator);
			}
		}
		return theValue;
	}
}
